﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace JYYQ.BMS
{
    public class DataTableHelper
    {
        public static DataTable ConvertToDataTable<T>(IList<T> list)
        {
            DataTable table = CreateTable<T>();
            Type entityType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
            foreach (T item in list)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item);
                table.Rows.Add(row);
            }
            return table;
        }

        public static IList<ChargeData> ConvertToList<T>(DataTable table)
        {
            if (table == null)
            {
                return null;
            }

            List<DataRow> rows = new List<DataRow>();

            foreach (DataRow row in table.Rows)
            {
                rows.Add(row);
            }

            return ConvertTo<ChargeData>(rows);
        }

        private static IList<ChargeData> ConvertTo<TChargeData>(IList<DataRow> rows)
        {
            IList<ChargeData> list = null;

            if (rows != null)
            {
                list = new List<ChargeData>();

                foreach (DataRow row in rows)
                {
                    ChargeData item = CreateItem(row);
                    list.Add(item);
                }
            }

            return list;
        }

        private static ChargeData CreateItem(DataRow row)
        {
            ChargeData obj = new ChargeData();
            if (row != null)
            {
                obj.Current = Convert.ToDouble(row["Current"]);
                obj.Hour = Convert.ToInt32(row["Hour"]);
                obj.Voltage = Convert.ToDouble(row["Voltage"]);
                obj.Minute = Convert.ToInt32(row["Minute"]);
            }

            return obj;
        }

        private static DataTable CreateTable<T>()
        {
            Type entityType = typeof(T);
            DataTable table = new DataTable(entityType.Name);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, prop.PropertyType);

            return table;
        }
    }
}